//
//  ConnectorLayoutView.m
//  CocoaSynth
//
//  Created by Thomas Dupont on 19/02/10.
//  Copyright 2010 Apple Inc. All rights reserved.
//

#import "ConnectorLayoutView.h"

#import "PortViewController.h"


@implementation ConnectorLayoutView

- (id)initWithFrame:(NSRect)frameRect
{
	if (self = [super initWithFrame:frameRect]) {
		draw = NO;
		mouse = NSMakePoint(0, 0);
		port = NSMakePoint(0, 0);
		image = [NSImage imageNamed:@"vco.png"];
	}
	return self;
}

- (BOOL) acceptsFirstResponder
{
	return YES;
}

- (void)drawRect:(NSRect)dirtyRect
{
	if (draw) {
		
		int distance = MAX(port.x, mouse.x) - MIN(port.x, mouse.x);
		
		NSPoint nearPort;
		nearPort.x = port.x;
		nearPort.y = port.y - 30 - distance/5;
		
		NSPoint nearMouse;
		nearMouse.x = mouse.x;
		nearMouse.y = mouse.y - 30 - distance/5;
		
		[[NSColor blackColor] set];
		
		NSBezierPath* path = [NSBezierPath bezierPath];
		
		[path setLineWidth:10];
		[path setLineCapStyle:NSRoundLineCapStyle];
		[path setLineJoinStyle:NSRoundLineCapStyle];
		
		[path moveToPoint:port];
		
		[path curveToPoint:mouse controlPoint1:nearPort controlPoint2:nearMouse];
		[path curveToPoint:port controlPoint1:nearMouse controlPoint2:nearPort];
		
		[path closePath];
		
		[path stroke];
	}
}

- (void)mouseMoved:(NSEvent *)theEvent
{
	mouse = [theEvent locationInWindow];
	mouse = [self convertPoint:mouse fromView:nil];
	if (draw) {
		[self setNeedsDisplay:YES];
	}
}

- (void)drawTemporaryConnectorFrom:(PortViewController*)aPort
{
	NSRect portFrame = [aPort view].frame;
	NSPoint portPoint;
	portPoint.x = portFrame.origin.x + portFrame.size.width / 2;
	portPoint.y = portFrame.origin.y + portFrame.size.height / 2;
	NSPoint point = [[[aPort module] view] convertPoint:portPoint toView:nil];
	port = [self convertPoint:point fromView:nil];
	draw = YES;
}

- (void)clearConnector
{
	draw = NO;
	[self setNeedsDisplay:YES];
}

@end
